<template>
  <div>
    <div class="one" style="position: fixed; top: 0; left: 0; right: 0;">
      <div class="one1" @click="fanhui">
        <van-icon name="arrow-left"/>
      </div>
      <div class="one2">在线客服</div>
      <div class="one1"></div>
    </div>
    <div style="margin-top: 70px"></div>

    <div style="width: 100%;" v-for="item in chatHistory">
      <div class="kefu" v-if="item.status == 1">
        <van-image
            src="https://lsz-jyyx.oss-cn-beijing.aliyuncs.com/lsz-jyyx/2024/7/29/889bbc836b1f4354809eaecf36dead4c.jpg"
            width="50px"
            height="50px"
            style="margin-top: -25px; margin-left: 10px; border-radius: 2px;"
        />
        <div class="kefu1" :style="{ maxWidth: '260px' }">
          <div style="padding: 0 5px 0 5px; line-height: 25px">{{ item.content }}</div>
        </div>
      </div>
      <div class="yong" v-if="item.status == 2">
        <div class="yong1" :style="{ maxWidth: '260px' }">
          <div style="padding: 0 5px 0 5px; line-height: 25px;">{{ item.content }}</div>
        </div>
        <van-image
            :src=user.photo
            width="50px"
            height="50px"
            style="margin-top: -25px; margin-right: 10px; border-radius: 5px;"
        />
      </div>
    </div>


    <div>
      <p>{{ responseText }}</p>
    </div>


    <div style="margin-top: 60px"></div>


    <div style="width: 100%;display: flex">
      <div style="position: fixed; bottom: 0;left: 0; width: 85%;background: white">
        <van-cell-group inset>
          <van-field
              v-model="value"
              rows="1"
              autosize
              type="textarea"
          />
        </van-cell-group>
      </div>
      <van-button type="primary" @click="fasong"
                  style="position: fixed;
                  bottom: 0;left: 0;
                  width: 15%;
                  margin-left: 83%;
                  background: #51b8ff;
                  height: 44px;
                  width: 74px;
                  border: white 1px solid;
                  margin-top: -10px">发送
      </van-button>
    </div>


  </div>
</template>

<script>
import Vue from 'vue';
import {chatAdd, selectByIp, AIReply, aliyunAi} from "@/api/SetUp/chat/chat";

export default {
  directives: {
    maxWidth: {
      bind(el, binding) {
        const maxWidth = binding.value;
        el.style.maxWidth = `${maxWidth}px`;
        window.addEventListener('resize', () => {
          el.style.maxWidth = `${maxWidth}px`;
        });
      },
      unbind(el) {
        window.removeEventListener('resize', () => {
          el.style.maxWidth = '';
        });
      }
    }
  },
  data() {
    return {
      chatList: [],
      user: JSON.parse(localStorage.getItem('login')),
      value: null,
      chatHistory: [],
      chat: {
        id:'',
        content: '',
        status:'',
      },
      responseText: '',
      count:0,
      content:'',
    };
  },
  created() {
  },
  methods: {
    // 发送聊天内容的方法
    fasong() {
      this.chat.content = this.value;
      this.content = this.value;
      this.chat.id = this.count++;
      this.chat.status =2;
      // 清空输入框内容
      this.value=''
      // 创建一个新的对象拷贝
      const newChat = { ...this.chat };
      this.chatHistory.push(newChat); // 向 chatHistory 中添加新的聊天记录
      console.log(this.chatHistory);
      this.keAdd();
    },

// 处理回复的方法
    /**
     * 智谱Ai
     */
    async keAdd() {
      try {
        // 初始化响应文本
        this.chat.content = '';
        this.chat.id = this.count++;
        this.chat.status =1;
        const newChat = { ...this.chat };
        this.chatHistory.push(newChat); // 向 chatHistory 中添加新的聊天记录
        const response = await AIReply(this.content).then()

        // 遍历响应数据
        let index = 0;
        const updateContent = () => {
          if (index < response.data.length) {
            const dataItem = response.data[index];
            if ( dataItem.choices[0].delta.content) {
              this.chatHistory[this.chatHistory.length - 1].content += dataItem.choices[0].delta.content;
              Vue.nextTick(() => {
                const responseDiv = document.querySelector('.response-content');
                responseDiv.innerHTML = this.chatHistory[this.chatHistory.length - 1].content;
              });
            }
            index++;
            setTimeout(updateContent, 100); // 每次更新后延迟 100 毫秒
          }
        };

        updateContent();
      } catch (error) {
        console.error('Error:', error);
      }
    },
    /**
     * aliyun通意
     * @returns {Promise<void>}
     */
    // async keAdd() {
    //     // 初始化响应文本
    //     this.chat.content = '';
    //     this.chat.id = this.count++;
    //     this.chat.status =1;
    //     const newChat = { ...this.chat };
    //     this.chatHistory.push(newChat); // 向 chatHistory 中添加新的聊天记录
    //
    //     const response = new EventSource('http://localhost:11219/SetUp/aliyunAi/ask/'+ this.content);
    //     // 遍历响应数据
    //     var a=0
    //     response.onmessage = (event) => {
    //         this.chatHistory[this.chatHistory.length - 1].content += event.data;
    //     };
    //     response.onerror = (error) => {
    //     console.error('SSE 错误：', error);
    //   };
    // },





    fanhui() {
      this.$router.push("/mine")
    },


  }
}

</script>

<style scoped>
.one {
  width: 100%;
  height: 60px;
  display: flex;
  background: white;
  z-index: 1000;
}

.one1 {
  width: 10%;
  height: 60px;
  line-height: 60px;
  font-size: 20px;

}

.one2 {
  width: 80%;
  height: 60px;
  line-height: 60px;
  font-size: 20px;
}

.kefu {
  width: 90%;
  padding-right: 10%;
  display: flex;
  margin-top: 20px;
}

.yong {
  width: 90%;
  padding-left: 10%;
  display: flex;
  margin-top: 20px;
  justify-content: flex-end; /* 新增属性 */

}

.kefu1 {
  margin-left: 15px;
  background: whitesmoke;
  border-radius: 5px;
  text-align: left;
  padding: 8px 3px 8px 3px;
  margin-top: -5px;
}

.yong1 {
  margin-right: 15px;
  background: #51b8ff;
  border-radius: 5px;
  text-align: left;
  padding: 8px 3px 8px 3px;
  margin-top: -5px;
}

</style>
